// 将element添加到scene中
function addElementToScene(scene, element) {
  scene.appendChild(element);
}

// 返回 min<=x<max间的数
function getRandomArbitrary(min, max) {
  return Math.random() * (max - min) + min;
}
// 返回随机RGB颜色
function getRandomColor() {
  const letters = '0123456789ABCDEF';
  let color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}
// 返回平面上以centerPoint为中点,角度分布在startAngel与endAngel间，半径分布在minRadius和maxRadius中间的随机点坐标
function getRandomPosition_circle(centerPoint, startAngel, endAngel, minRadius, maxRadius) {
  const randomRadius = getRandomArbitrary(minRadius, maxRadius);
  const randomAngel = getRandomArbitrary(startAngel, endAngel) / (Math.PI * 2);
  const position_x = centerPoint.x + randomRadius * Math.cos(randomAngel);
  const position_z = centerPoint.z + randomRadius * Math.sin(randomAngel);
  const position_y = centerPoint.y;
  const res = {
    x: position_x,
    y: position_y,
    z: position_z
  }
  // console.log('res', res);
  return res;
}


// 设置记分板上分数
function setScore(element, score) {
  element.setAttribute('text', {
    value: score
  })
}

function setUserInfo(element, userInfo) {
  element.setAttribute('text', {
    value: userInfo
  })

}
// 设置计分板用户信息
function setScoreBoardUserInfo() {
  const info_left = document.querySelector('#id_left');
  const info_leftValue = info_left.getAttribute('text').value;

  const info_right = document.querySelector('#id_right');
  const info_rightValue = info_right.getAttribute('text').value;

  const userInfoData = {
    localuserId: localuserId,
    enemyId: info_leftValue
  }

  if (shootGameLock === false) {//battle-button未被锁，可以设置用户名
    if (info_leftValue === 'id_left' && info_leftValue !== localuserId) {
      // 设置自己这边显示的信息
      info_left.setAttribute('text', {
        value: localuserId
      })
      // 广播给自己的信息
      NAF.connection.broadcastData(dataType_userInfo_left, userInfoData);
    }
    // 如果左边面板id被设置成对手id，则可以设置右边面板为自己id；然后广播给其他用户(有用户对战过程中不允许设置)
    if (info_leftValue !== 'id_left' && info_leftValue !== localuserId) {
      info_right.setAttribute('text', {
        value: localuserId
      })
      NAF.connection.broadcastData(dataType_userInfo_right, userInfoData);
    }
  }


}

// 设置计分板分数
function setScoreBoardUserScore(score = 2) {
  const info_left = document.querySelector('#id_left');
  const info_right = document.querySelector('#id_right');
  const info_leftValue = info_left.getAttribute('text').value;
  const info_rightValue = info_right.getAttribute('text').value;
  // 原始分数
  const score_left = document.querySelector('#score_left');
  let originalScore_left = score_left.getAttribute('text').value;
  originalScore_left = Number(originalScore_left);
  const score_right = document.querySelector('#score_right');
  let originalScore_right = score_right.getAttribute('text').value;
  originalScore_right = Number(originalScore_right);
  console.log('info_leftValue', info_leftValue);
  console.log('localuserId', localuserId);
  // 注意只有当前用户能击毁气球，如果左边是当前用户，则设置左边的分数
  if (info_leftValue === localuserId) {//左边是当前界面用户
    // local设置分数
    const newScore = originalScore_left + score;
    setScore(score_left, newScore);
    const userScoreData = {
      userIdOfScore: localuserId,
      score: newScore
    }
    // remote设置分数
    NAF.connection.broadcastData(dataType_userScore_left, userScoreData);
  }
  if (info_rightValue === localuserId) {//右边是当前界面用户
    // local设置分数
    const newScore = originalScore_right + score;
    setScore(score_right, newScore);
    const userScoreData = {
      userIdOfScore: localuserId,
      score: newScore
    }
    // remote设置分数
    NAF.connection.broadcastData(dataType_userScore_right, userScoreData);
  }

}


function gameOver() {
  const info_left = document.querySelector('#id_left');
  const info_right = document.querySelector('#id_right');
  const info_leftValue = info_left.getAttribute('text').value;
  const info_rightValue = info_right.getAttribute('text').value;

  const score_left = document.querySelector('#score_left');
  let originalScore_left = score_left.getAttribute('text').value;
  originalScore_left = Number(originalScore_left);
  const score_right = document.querySelector('#score_right');
  let originalScore_right = score_right.getAttribute('text').value;
  originalScore_right = Number(originalScore_right);
  const data = {//默认是分数相等情况下
    winnerId: '',
    failurerId: '',
    isEqual: true,
    player1Id: info_leftValue,
    player2Id: info_rightValue
  };
  if (originalScore_left < originalScore_right) {//右边玩家赢
    data.winnerId = info_rightValue,
      data.failurerId = info_leftValue,
      data.isEqual = false
  }
  if (originalScore_left > originalScore_right) {//右边玩家赢
    data.winnerId = info_leftValue,
      data.failurerId = info_rightValue,
      data.isEqual = false
  }
  // 如果左边的是玩家之一，本地显示消息
  if (info_leftValue === localuserId) {
    if (data.isEqual === false) {
      if (data.winnerId === info_leftValue) {
        showMessage_shootGame('You win');
        // alert('You win');
      } if (data.winnerId === info_rightValue) {
        showMessage_shootGame('You lose');
        // alert('You lose');
      }
    } else {
      showMessage_shootGame('你俩平局');
      // alert('你俩平局');
    }
    // 如果左边是当前玩家，就把信息发送给右边。这样就只会发送一次
    NAF.connection.sendData(info_rightValue, dataType_shootGame_result, data)
    // 给除了玩家之外的其他用户广播比赛结果
    NAF.connection.broadcastData(dataType_shootGame_result_others, data);

    shootGameLock = false;//游戏结束，本地解锁
    // 远程解锁
    NAF.connection.broadcastData(dataType_shootGameLock, {
      shootGameLock: shootGameLock
    });
    // 游戏结束本地重置记分板信息
    console.error('locally resetScoreBoard');
    resetScoreBoard();
  }
}

function isPlayerJudge(player1Id, player2Id, localuserId) {
  let judge = false;
  console.error('player1Id', player1Id);
  console.error('player2Id', player2Id);
  console.error('localuserId', localuserId);
  if (player1Id === localuserId || player2Id === localuserId) {
    judge = true;
  }
  return judge;
}

// 控制射击游戏是否开始
function playerStartGame() {
  const info_left = document.querySelector('#id_left');
  const info_leftValue = info_left.getAttribute('text').value;

  const info_right = document.querySelector('#id_right');
  const info_rightValue = info_right.getAttribute('text').value;
  const players = {
    leftUserId: info_leftValue,
    rightUserId: info_rightValue
  }
  // 本地启动游戏
  console.error('Locally start shoot game');
  startShootGame();
  // 远程启动游戏
  if (info_leftValue === localuserId) {
    NAF.connection.sendData(info_rightValue, dataType_startShootGame, players);
  } else {
    NAF.connection.sendData(info_leftValue, dataType_startShootGame, players);
  }
  shootGameLock = true;//battle-btn本地加锁
  // 广播加锁信息
  NAF.connection.broadcastData(dataType_shootGameLock, {
    shootGameLock: shootGameLock
  })
}

// 计时器
function mazeCounterFunc(minTime = 0, maxTime = 60) {
  let increaseNumber = function () {
    let counter = null;
    minTime++;
    if (minTime < maxTime) {
      counter = setTimeout(increaseNumber, 1000);
      mazeCounter = minTime;
      console.log('self.mazeCounter ', self.mazeCounter);

    } else {
      console.error("Done");
      clearTimeout(counter);
    }
  }
  setTimeout(increaseNumber, 1000);
}

function setAvatarId() {
  const avatarId = document.querySelector('.avatarId');
  console.log('avatarId', avatarId);
  // console.log('avatarId',avatarId);
  avatarId.setAttribute('text', {
    value: localuserId
  })
}

function reset() {
  // let finishDlgElm = document.querySelector("#finishDialog")
  // finishDlgElm.setAttribute("style", "display: none");
  location.reload();
}

function mazeGamecont() {
  let finishDlgElm = document.querySelector("#finishDialog")
  finishDlgElm.setAttribute("style", "display: none");
}
// 找到彩蛋显示消息
function showEggFoundMessage(time=10000) {
  let finishDlgElm = document.querySelector("#finishDialog")
  finishDlgElm.setAttribute("style", "display: block");
  // 自己找到彩蛋，显示时间长一点
  setTimeout(() => {
    finishDlgElm.setAttribute("style", "display: none");
  }, time);
  // 显示时间
  findEggTime = dayjs();
  console.log('findEggTime', findEggTime);
  console.log('enterMazeTime', enterMazeTime);
  const timeInterval = findEggTime - enterMazeTime;
  console.log('findEggTime-enterMazeTime', timeInterval);
  const timeIntervalSec = Math.floor(timeInterval / 1000);
  const timeCounter = document.querySelector('#counter');
  timeCounter.textContent = timeIntervalSec;
  console.log('counter', counter);

  const userId = document.querySelector('#userId');
  userId.textContent = '你';

  // 显示彩蛋个数
  if (localStorage.getItem("my-maze-data") != undefined) {
    let data = JSON.parse(localStorage.getItem("my-maze-data"));
    console.error('locally my-maze-data');
    endNumber = data.endNumber;
  }
  const eggNumberEle = document.querySelector('#eggNumber');
  eggNumberEle.textContent = endNumber;
  console.log('endNumber', endNumber);

  const eggFoundNumberEle = document.querySelector('#foundEggNumber');
  eggFoundNumberEle.textContent = foundEggNumber;
  console.log('foundEggNumber', foundEggNumber);

  // 广播找到彩蛋消息
  NAF.connection.broadcastData(dataType_eggFound, {
    time: timeIntervalSec, userId: localuserId, endNumber: endNumber,
    foundEggNumber:foundEggNumber
  });
}

function showMessage_shootGame(message = "这是比赛结果", time = 20000) {
  const shootGameResEle = document.querySelector('#shootGameRes');
  shootGameResEle.textContent = message;

  const finishDlgElm = document.querySelector("#finishDialog")
  finishDlgElm.setAttribute("style", "display: block");
  // 自己找到彩蛋，显示时间长一点
  setTimeout(() => {
    finishDlgElm.setAttribute("style", "display: none");
  }, time);


}

function resetScoreBoard() {
  const info_left = document.querySelector('#id_left');
  const info_right = document.querySelector('#id_right');
  const score_left = document.querySelector('#score_left');
  const score_right = document.querySelector('#score_right');
  // 游戏结束重置记分板信息
  info_left.setAttribute('text', {
    value: originalValue_userInfo_left
  });
  info_right.setAttribute('text', {
    value: originalValue_userInfo_right
  });
  score_left.setAttribute('text', {
    value: originalValue_userScore_left
  });
  score_right.setAttribute('text', {
    value: originalValue_userScore_right
  });
  //  info_left.value = originalValue_userInfo_left;
  //  info_right.value = originalValue_userInfo_right;
  //  score_left.value = originalValue_userScore_left;
  //  score_right.value = originalValue_userScore_right;
}

function hideEle(el) {
  el.setAttribute("style", "display: none");
}

function  setHvalue(el,value) {
  el.textContent=value;
 
}
// 处理蒙层逻辑
function dealSceneLoad(elToHide,elToChange, minTime = 0, maxTime = 5) {
  let increaseNumber = function () {
    console.log('minTime', minTime);
    minTime++;
    if (minTime < maxTime ) {
      setTimeout(increaseNumber, 1000);
      setHvalue(elToChange,sceneWaitTime-minTime);
    } else {
      // alert("Done");
      hideEle(elToHide);
    }
  }
  setTimeout(increaseNumber, 1000);

}

function showPortal(el,pos) {
  console.error('showPortal');
  console.log('el',el);
  el.setAttribute('position',pos);
  const portalWrapper=document.querySelector('.portalWrapper');
  portalWrapper.setAttribute('opacity',0.05);

}